
#include "init.h"


int listMailVar(int count, ...);
int listNum(int sock);
int listNum(int sock)
{
    char rec2[1024], list[6] = "LIST\r\n";
    bzero(rec2, strlen(rec2));
    
    write(sock, list, strlen(list));
    
    read(sock, rec2, sizeof(rec2));

    
    char seg[] = "\r\n";
    char *token;
    int num;
    int mailSize;
    int a = 1;
    token = strtok(rec2, seg);
    sscanf(token, "+OK %d %d", &num, &mailSize);
    return num;
}


int listMailVar(int count, ...)
{
    
    double sum = 0;
    double sum_sq = 0;
    va_list args;
    va_start(args, count);
    if (count == 1 || count == 2)
    {
        int sock = va_arg(args, int);
        char rec[1024], list[6] = "LIST\r\n";
        bzero(rec, strlen(rec));
        
        write(sock, list, strlen(list));
        
        read(sock, rec, sizeof(rec));

        
        char seg[] = "\r\n";
        char *token;
        int num;
        int mailSize;
        int a = 1;
        token = strtok(rec, seg);

        if (count == 1)
        {
            sscanf(token, "+OK %d %d", &num, &mailSize);
            printf("\nThere are %d emails in your mailbox, accFounting for %d bits.\nThey are:\n-------------------\n", num, mailSize);
            printf("#No\tSize\n");
            
            bzero(&num, sizeof(num));
            bzero(&mailSize, sizeof(mailSize));
            while ((token = strtok(NULL, seg)) != NULL)
            {
                if (*token != '.')
                {
                    int num1, num2;
                    sscanf(token, "%d %d", &num1, &num2);
                    printf("%d\t%d\n", num1, num2);
                }
            }

            bzero(seg, strlen(seg));
        }
        else
        {
            int temp = va_arg(args, int);
            int index = 1;
            while ((token = strtok(NULL, seg)) != NULL)
            {
                if (*token != '.')
                {
                    int num1, num2;
                    sscanf(token, "%d %d", &num1, &num2);
                    if (index == temp)
                    {
                        printf("%d\t%d\n", num1, num2);
                    }
                    index++;
                }
            }
            
            if (temp >= index)
            {
                printf("\nThe email does not exist!!! Please try again.\n\n");
                bzero(seg, strlen(seg));
                return 1;
            }
        }
        bzero(seg, strlen(seg));
    }
    else
    {
        printf("Wrong Input\n");
        return 1;
    }
    va_end(args);
    return 0;
}
